<?php
/**
 * 岗位管理
 *
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class RoleController extends BaseController {

	public function index(){
		$wheres = array();
		$wheres['is_deleted'] = array('neq', 1);
		$roles = M("Role")->field("role_id,role_name,parent_role")->where( $wheres )->select();
		$_roles = array();
        foreach( $roles as $vs ){
            $_roles[$vs['role_id']] = $vs;
        }
        if( 1 == $this->m_user['user_id'])
	       $arr = list_to_tree($roles,'role_id','parent_role', '_child', 0);
       else{
       		$arr = array();
       		$arr[] = $_roles[$this->m_user['role_id']];
		    $arr[0]['_child'] =  list_to_tree($roles,'role_id','parent_role', '_child', $this->m_user['role_id']);
       }
		$re = array('rcode'=>1,'data'=>0,'msg'=>'ok');
		$re['data'] = $arr;
		e_json( $re );
	}

	/**
	 * 根据提交的岗位ID获取该岗位绑定的权限
	 * @return [type] [description]
	 */
	public function edit(){
		$re = array('rcode'=>0,'data'=>0,'msg'=>'ok');
		$MRole = D("Role");
		$wheres = array();

		if( IS_GET ){
			$role_id = I("get.role_id",'false','intval');

			$where['is_deleted'] = array('neq', 1);
			if( $role_id ){
				$wheres['role_id'] = array('eq', $role_id );
				$drole = $MRole->where( $wheres )->find();
				$re['data'] = $drole;
				$re['data']['rights'] = array();
				if( $drole ){
					$MRoleRights = M('RoleRights');
					$wherec = array();
					$wherec['role_id'] = array('eq', $role_id );
					$_arr = $MRoleRights->field("right_id")->where( $wherec )->select();
					foreach( $_arr as $va ){
						$re['data']['rights'][] = intval( $va['right_id'] );
					}
					$re['rcode'] = 1;
					$re['msg'] = 'OK';
				}
				else
					$re['msg'] = '查询对象不存在';
			}
			else
				$re['msg'] = '提交参数错误';
		}
		else if( IS_POST ){
			$MRole->create();
			$rights = I('post.rights','');
			$role_id = I("post.role_id",'','intval');
			$MRole->role_id = $role_id;
			if( $role_id && $rights && is_array($rights)&&count( $rights)!=0 ){
				$r = $MRole->edit_role( $rights );
				if( $r['r'] ){
					$re['rcode'] = 1;
					$re['msg'] = 'OK';
				}
				else
					$re['msg'] = $r['i'];
			}
			else{
				$re['rcode'] = -1;
				$re['msg'] = "提交参数错误";
			}

		}
		e_json( $re );
	}

	public function add(){
		$res = array('rcode'=>0,'data'=>$edit,'msg'=>'server Busy!');
		$MRole = D("Role");
		$MRole->create();
		$rights = I('post.rights','false');
		if( $rights )
			$rights = (array)$rights;
		$r = $MRole->add_role( $rights );
		if( $r['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
		}
		else
			$res['msg'] = $r['i'];
		e_json( $res );
	}


	public function delete(){
            //delete
	}
}